﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;

/// <summary>
/// BaiDuAI 的摘要说明
/// </summary>
public class BaiduAI
{
    protected const string BaiduAppName = "FullAIApp";
    public BaiduAI() { }

	public static Dictionary<string, object> AppAuthParam()
    {
        try
        {
            string json = SettingHelper.ReadSiteSetting();
            Dictionary<string, object> dict = json.Json2Dictionary();
            dict = dict["site"].ToString().Json2Dictionary();
            dict = dict["thirdapp"].ToString().Json2Dictionary();
            List<Dictionary<string, object>> baidu = dict["baidu"].ToString().Json2List();
            Dictionary<string, object> para = baidu.FirstOrDefault(x => x["appname"].ToString() == BaiduAppName);
            return para;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static String getAccessToken()
    {
        string cache_accessToken = string.Format("{0}_AccessToken", BaiduAppName);
        if (Cacheing.Get(cache_accessToken) != null) return Cacheing.Get(cache_accessToken).ToString();
        Dictionary<string, object> para = AppAuthParam();
        string apiKey = para["APIKey"].ToString();
        string secretKey = para["SecretKey"].ToString();
        String authHost = "https://aip.baidubce.com/oauth/2.0/token";

        HttpClient client = new HttpClient();
        List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
        paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
        paraList.Add(new KeyValuePair<string, string>("client_id", apiKey));
        paraList.Add(new KeyValuePair<string, string>("client_secret", secretKey));

        HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
        String result = response.Content.ReadAsStringAsync().Result;
        Dictionary<string, object> res = result.Json2Dictionary();
        int expires_in = 2592000;
        int.TryParse(res["expires_in"].ToString(), out expires_in);
        Cacheing.Add(cache_accessToken, res["access_token"].ToString(), expires_in);
        return res["access_token"].ToString();
    }

}